<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
  <script src="./rem.js"></script>
  <title>Map</title>
</head>
<style type="text/css">
  * {
    padding: 0;
    margin: 0;
  }

  html,
  body {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  #map {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .loadinggif {
    width: .5rem;
    height: .5rem;
  }

  .gm-style-mtc {
    display: none;
  }

  .gmnoprint {
    display: none !important;
  }

  .gmnoprint.gm-bundled-control.gm-bundled-control-on-bottom {
    display: none;
  }

  .gm-control-active.gm-fullscreen-control {
    display: none;
  }

  [class^="https://maps.google.com/maps"] {
    display: none !important;
  }

  .controls {
    margin-top: 10px;
    border: 1px solid transparent;
    border-radius: 2px 0 0 2px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    height: 32px;
    outline: none;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  }

  #pac-input {
    width: 6.8rem;
    height: .8rem;
    box-sizing: border-box;
    position: fixed !important;
    top: 1rem !important;
    left: .32rem !important;
    padding: 0 .32rem;
    right: .32rem !important;
  }

  .pac-logo:after {
    display: none !important;
  }

  .btn {
    position: fixed;
    right: .4rem;
    bottom: 2rem;
    width: 1.2rem;
    height: 1.2rem;
    background-image: linear-gradient(45deg, #2979ff, #2979ff);
    font-size: .24rem;
    line-height: 1.2;
    color: #fff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all ease .3s;
    box-shadow: 0px 3px 15px rgba(0, 0, 0, 0.2);
  }

  .btn1 {
    bottom: 4rem;
    background: #fff;

    img {
      width: 22px;
    }
  }
</style>

<body>
  <!-- <div class="title">
			<img class="usericon" id="user" src="../image/3.png" >
			<span class="title_tip">位置</span>
			<span class="usericon"></span>
		</div> -->
  <input id="pac-input" class="controls" type="text" placeholder="Search Box">
  <div id="map">
    <img class="loadinggif" src="./loading.gif">
  </div>
  <div id="btn" class="btn" style="text-align: center;">OK<br>choose</div>
  <div id="btn1" class="btn btn1" style="text-align: center;">
    <img src="./currentAdd.png">
  </div>
</body>
<script src="./jquery-3.2.1.min.js"></script>
<script src="./uni.webview.1.5.2.js"></script>

<!-- https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js -->
<!-- <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script> -->
<!-- AIzaSyC8jQSK_m7WU5QLV6zemkns14z_45TRmJw-->
<script
  src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC8jQSK_m7WU5QLV6zemkns14z_45TRmJw&libraries=places&callback=initMap"
  async defer></script>
<script type="text/javascript" charset="utf-8">
  var lngtxt = "";
  var lattxt = "";
  var addresstxt = "";

  var isMaploading = false;
  var isUniAppJSBridgeReady = false;

  var map;
  var marker;
  var infowindow;
  var geocoder;
  var markersArray = [];
  var language = getParam('language') || 'en';
  var lp = {
    "OK<br/>choose": {
      "ar": "حدد",
      "en": "OK<br/>choose"
    }
  }
  var lps = {
    "Search Box": {
      "ar": "بحث .",
      "en": "Search Box"
    }
  }
  document.getElementById('btn').innerHTML = lp['OK<br/>choose'][language];
  $("#pac-input").attr("placeholder", lps['Search Box'][language])
  // document.getElementById('pac-input').val() = lps['搜索'][language];
  // console.log(document.getElementById('pac-input').placeholder)

  /**
   * 获取指定的URL参数值 
   * URL:http://www.quwan.com/index?name=tyler 
   * 参数：paramName URL参数 
   * 调用方法:getParam("name") 
   * 返回值:tyler 
   */
  function getParam (paramName)
  {
    paramValue = "", isFound = !1;
    if (this.location.search.indexOf("?") == 0 && this.location.search.indexOf("=") > 1) {
      arrSource = unescape(this.location.search).substring(1, this.location.search.length).split("&"), i = 0;
      while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0]
        .toLowerCase() ==
        paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
    }
    return paramValue == "" && (paramValue = null), paramValue;
  }
  let addressInfo = JSON.parse(getParam('riderList')) || {};
  let uni = webUni
  document.addEventListener("UniAppJSBridgeReady", function ()
  {
    console.log("初始化uniapp的API成功");
    // 开始
    uni.getEnv(function (res)
    {
      console.log("当前环境", res);
      this.isUniAppJSBridgeReady = true;
      initMap(true);
    });	// 结束

    document.getElementById('btn').addEventListener('click', function ()
    {
      console.log('准备点击')
      if (!isMaploading || !isUniAppJSBridgeReady) return false;
      let location = {
        action: 'chooseaddress',
        latitude: lattxt,
        longitude: lngtxt,
        addresstxt: addresstxt
      }
      var queryString = window.location.search.substring(1); // 移除?字符
      var params = new URLSearchParams(queryString);
      var type = params.get('type');
      var id = params.get('id');
      if (type == 'edit') {
        console.log('编辑点击点击')
        // uni.navigateTo({
        // 	url: "/pages/edit-house/edit-house?id="+id+'&data='+JSON.stringify(data)
        // })
        // })
        uni.webView.postMessage({
          data: {
            action: 'chooseaddress',
            latitude: lattxt,
            longitude: lngtxt,
            addresstxt: addresstxt
          }
        })
        setTimeout(() =>
        {
          uni.webView.navigateBack() //返回上个页面
        }, 800)
      } else {
        console.log('新增点击点击')
        let data = {
          action: 'chooseaddress',
          latitude: lattxt,
          longitude: lngtxt,
          addresstxt: addresstxt
        }

        var timer = setTimeout(function ()
        {
          clearInterval(timer);
          console.log("谷歌地图返回:", data)

          uni.postMessage({
            data
          })

          uni.navigateBack()
        }, 10)
        console.log('uni', uni)
        // setTimeout(() => {
        // 	uni.webView.navigateBack() //返回上个页面
        // }, 800)
        // uni.navigateTo({
        // 	url: '/pages/submit/submit?data='+JSON.stringify(data)
        // })
      }
    })
    // 获取当前位置
    document.getElementById('btn1').addEventListener('click', function ()
    {
      console.log('准备点击')
      initMap(true)
    })
  });




  function initMap (mode)
  {

    if (!mode) isMaploading = true;
    if (!isMaploading || !isUniAppJSBridgeReady) return false;


    // 获取当前地理位置
    if (navigator.geolocation) {

      if (addressInfo.latitude) {
        lattxt = addressInfo.latitude;
        lngtxt = addressInfo.longitude;
        initAutocomplete();
        console.log(JSON.stringify(addressInfo));
        return false
      }
      navigator.geolocation.getCurrentPosition(function (position)
      {
        var coords = position.coords;
        lattxt = coords.latitude;
        lngtxt = coords.longitude;
        initAutocomplete()
      }, function (err)
      {
        console.log('navigator.geolocation error')
        lattxt = 12.879721;
        lngtxt = 121.774017;
        initAutocomplete()
      }, {
        enableHighAccuracy: true, //是否要求高精度的地理位置信息
        timeout: 10000, //对地理位置信息的获取操作做超时限制，如果再该事件内未获取到地理位置信息，将返回错误
        maximumAge: 60 * 1000 //设置缓存有效时间，在该时间段内，获取的地理位置信息还是设置此时间段之前的那次获得的信息，超过这段时间缓存的位置信息会被废弃
      })
    } else {
      // alert(globalLanguage.ditu.no_tip);
      alert("你的浏览器不支持HTML5来获取地理位置信息。");
    }
  }
  // function initMap() {
  // 	var map = new google.maps.Map(document.getElementById("map"), {
  // 		zoom: 13,
  // 		center: new google.maps.LatLng(34.439398,113.66728)
  // 	});
  // 	let arr =[]
  // 	for(let i=0;i<addressInfo.length;i++){
  // 		// console.log(new google.maps.LatLng(addressInfo[i].lat*1, addressInfo[i].lng*1))
  // 		var marker = new google.maps.Marker({
  // 			position: new google.maps.LatLng(addressInfo[i].lat*1, addressInfo[i].lng*1),
  // 			icon:'https://developers.google.cn/maps/documentation/javascript/images/custom-marker.png',
  // 			map: map
  // 		});
  // 	}
  // 	// var marker = new google.maps.Marker({
  // 	// 	position: location,
  // 	// 	map: map
  // 	// });

  // }


  function initAutocomplete ()
  {
    var latlng = new google.maps.LatLng(lattxt, lngtxt);
    console.log(google.maps.MapTypeId)
    var myOptions = {
      zoom: 13,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map'), myOptions);
    var map = new google.maps.Map(document.getElementById("map"), {
      zoom: 13,
      center: latlng
    });
    for (let i = 0; i < addressInfo.length; i++) {
      // console.log(new google.maps.LatLng(addressInfo[i].lat*1, addressInfo[i].lng*1))
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(addressInfo[i].lat * 1, addressInfo[i].lng * 1),
        icon: 'https://developers.google.cn/maps/documentation/javascript/images/custom-marker.png',
        map: map
      });
    }
    geocoder = new google.maps.Geocoder(); //实例化地址解析

    placeMarker({
      lat: lattxt,
      lng: lngtxt
    });

    //监听点击地图事件
    google.maps.event.addListener(map, 'click', function (event)
    {
      // console.log(JSON.stringify(event),'监听点击地图事件');
      placeMarker(event.latLng);
    });
    // Create the search box and link it to the UI element.
    var input = document.getElementById('pac-input');
    var searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // console.log(JSON.stringify(searchBox), 'searchBox类');
    // 将搜索框结果偏向当前地图的视口
    map.addListener('bounds_changed', function ()
    {
      searchBox.setBounds(map.getBounds());
      // console.log(JSON.stringify(map.getBounds()),'bounds_changed');
    });

    var markers = [];
    // Listen for the event fired when the user selects a prediction and retrieve
    // 侦听用户选择预测并检索时激发的事件

    // more details for that place.
    // 更多关于那个地方的细节。
    searchBox.addListener('places_changed', function ()
    {
      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }
      if (places.length == 1) {
        console.log(places)
        clearOverlays(infowindow); //清除地图中的标记
        marker = new google.maps.Marker({
          position: places[0].geometry.location,
          map: map
        });
        markersArray.push(marker);
        attachSecretMessage(marker, places[0].geometry.location, places[0].formatted_address + places[0]
          .name);
        var bounds = new google.maps.LatLngBounds();

        if (places[0].geometry.viewport) {
          // Only geocodes have viewport.
          bounds.union(places[0].geometry.viewport);
        } else {
          bounds.extend(places[0].geometry.location);
        }
        map.fitBounds(bounds);
        // console.log(JSON.stringify(places[0].geometry.location))
        lattxt = places[0].geometry.location.lat();
        lngtxt = places[0].geometry.location.lng();
        // console.log('lattxt',lattxt);
        addresstxt = places[0].formatted_address + (places[0].formatted_address.name || '');
        return;
      }

      return false;

      // Clear out the old markers.
      markers.forEach(function (marker)
      {
        marker.setMap(null);
      });
      markers = [];

      // For each place, get the icon, name and location.
      var bounds = new google.maps.LatLngBounds();
      places.forEach(function (place)
      {
        if (!place.geometry) {
          console.log("Returned place contains no geometry");
          return;
        }
        var icon = {
          url: place.icon,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25)
        };
        //console.log(place.geometry.location.lat());
        mapClick(place.geometry.location.lng(), place.geometry.location.lat(), place.name);
        // Create a marker for each place.
        markers.push(new google.maps.Marker({
          map: map,
          // icon: icon,
          title: place.name,
          position: place.geometry.location
        }));

        if (place.geometry.viewport) {
          // Only geocodes have viewport.
          // 只有地理代码才有视区。
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
      map.fitBounds(bounds);
    });


  }

  function placeMarker (location)
  {
    clearOverlays(infowindow); //清除地图中的标记
    marker = new google.maps.Marker({
      position: location,
      map: map
    });
    markersArray.push(marker);
    //根据经纬度获取地址
    if (geocoder) {
      geocoder.geocode({
        'location': location
      }, function (results, status)
      {
        console.log(results)
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[0]) {
            attachSecretMessage(marker, results[0].geometry.location, results[0].formatted_address);
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }
  }

  //在地图上显示经纬度地址
  function attachSecretMessage (marker, piont, address)
  {
    lattxt = piont.lat()
    lngtxt = piont.lng()
    addresstxt = address
    var message = "<b>Coordinate:</b>" + piont.lat() + " , " + piont.lng() + "<br />" + "<b>Address:</b>" + address;
    var infowindow = new google.maps.InfoWindow({
      content: message,
      size: new google.maps.Size(50, 50)
    });
    infowindow.open(map, marker);
    if (typeof (mapClick) == "function") mapClick(piont.lng(), piont.lat(), address);
  }

  //删除所有标记阵列中消除对它们的引用
  function clearOverlays (infowindow)
  {
    if (markersArray && markersArray.length > 0) {
      for (var i = 0; i < markersArray.length; i++) {
        markersArray[i].setMap(null);
      }
      markersArray.length = 0;
    }
    if (infowindow) {
      infowindow.close();
    }
  }

  function setiInit ()
  {
    // 页面加载显示默认lng lat address---begin
    if (lattxt != '' && lngtxt != '' && addresstxt != '') {
      var latlng = new google.maps.LatLng(lattxt, lngtxt);
      marker = new google.maps.Marker({
        position: latlng,
        map: map
      });
      markersArray.push(marker);
      attachSecretMessage(marker, latlng, addresstxt);
    }
  }

  function mapClick (lng, lat, address)
  {
    // window.parent.document.getElementById("address_lng").value = lng;
    // window.parent.document.getElementById("address_lat").value = lat;
    // window.parent.document.getElementById("address").value = address;
  }
  window.onload = function ()
  {
    setiInit();
  }
</script>

</html>